import { defineStore } from 'pinia'
import authApi from '@/api/auth'

export const useAuthStore = defineStore('auth', {
  state: () => ({
    userinfoId: localStorage.getItem('userinfoId') || '',
    roleId: localStorage.getItem('roleId') || '',
    nickName: localStorage.getItem('nickName') || '',
    status: localStorage.getItem('status') || '',
    avatar: localStorage.getItem('avatar') || '', // 新增：存储头像地址（默认空字符串）
    loading: false
  }),
  getters: {
    isLoggedIn: (state) => !!state.userinfoId && !!state.roleId && !!state.status,
    isSuperAdmin: (state) => state.roleId === '4',
    isMerchant: (state) => state.roleId === '3',
    isDoctor: (state) => state.roleId === '2',
    isUserNormal: (state) => state.status === '1',
    // 新增：获取完整头像地址（处理可能的相对路径，可选）
    fullAvatarUrl: (state) => {
      // 若后端返回的是相对路径，可在此拼接基础域名（根据实际情况调整）
      return state.avatar ? (state.avatar.startsWith('http') ? state.avatar : `https://${state.avatar}`) : ''
    }
  },
  actions: {
    /**
     * 登录：新增 avatar 字段存储
     */
    login(userData) {
      try {
        this.loading = true
        const { userinfoId, roleId, nickName, status, avatar } = userData
        
        // 转字符串存储（避免类型冲突）
        this.userinfoId = userinfoId.toString()
        this.roleId = roleId.toString()
        this.nickName = nickName || ''
        this.status = status.toString()
        this.avatar = avatar || '' // 存储头像地址（无需转字符串，本身就是URL）
        
        // 同步到本地存储（刷新不丢失）
        localStorage.setItem('userinfoId', this.userinfoId)
        localStorage.setItem('roleId', this.roleId)
        localStorage.setItem('nickName', this.nickName)
        localStorage.setItem('status', this.status)
        localStorage.setItem('avatar', this.avatar) // 新增：持久化头像
      } catch (error) {
        console.error('登录状态存储失败：', error)
        throw error
      } finally {
        this.loading = false
      }
    },

    /**
     * 退出登录：清除头像状态
     */
    async logout() {
      try {
        await authApi.logout() // 后端无退出接口可删除此行
      } catch (error) {
        console.error('退出登录失败：', error)
      } finally {
        // 清除所有状态（含 avatar）
        this.userinfoId = ''
        this.roleId = ''
        this.nickName = ''
        this.status = ''
        this.avatar = ''
        this.loading = false
        
        // 清除本地存储（含 avatar）
        localStorage.removeItem('userinfoId')
        localStorage.removeItem('roleId')
        localStorage.removeItem('nickName')
        localStorage.removeItem('status')
        localStorage.removeItem('avatar') // 清除头像
        localStorage.removeItem('rememberUser')
      }
    },

    /**
     * 强制清除状态：同步清除头像
     */
    clearUserState() {
      this.userinfoId = ''
      this.roleId = ''
      this.nickName = ''
      this.status = ''
      this.avatar = ''
      this.loading = false
      
      localStorage.removeItem('userinfoId')
      localStorage.removeItem('roleId')
      localStorage.removeItem('nickName')
      localStorage.removeItem('status')
      localStorage.removeItem('avatar')
      localStorage.removeItem('rememberUser')
    }
  }
})